﻿// outerHTML function
jQuery.fn.extend({
    outerHtml: function (replacement) {
        // We just want to replace the entire node and contents with
        // some new html value
        if (replacement) {
            return this.each(function () { $(this).replaceWith(replacement); });
        }

        /*
        * Now, clone the node, we want a duplicate so we don't remove
        * the contents from the DOM. Then append the cloned node to
        * an anonymous div.
        * Once you have the anonymous div, you can get the innerHtml,
        * which includes the original tag.
        */
        var tmpNode = $("<div></div>").append($(this).clone());
        var markup = tmpNode.html();

        // Don't forget to clean up or we will leak memory.
        tmpNode.remove();
        return markup;
    }
});

function AddTraveler() {
    if (window.travelersCount < 5) {
        var firstRow = $("table tr#Traveler_0").clone().outerHtml();
        var newRow = firstRow.replace(/\[0\]/g, "[" + window.travelersCount + "]").replace(/_0/g, "_" + window.travelersCount).replace(/AddNewTraveler/g, "RemoveTraveler");
        $("table#Travelers").append(newRow);

        $("#RemoveTraveler_" + window.travelersCount).attr("value", removeTravelerText);

        $("#RemoveTraveler_" + window.travelersCount).click(RemoveTraveler);

        window.travelersCount++;

        // fix the alternating row color
        for (var i = 0; i < window.travelersCount; i++) {
            var elem = $("table tr").regex("id", "^Traveler_" + i + "$");

            if (i % 2 == 0) {
                elem.removeClass("ui-state-highlight");
                elem.addClass("ui-widget-content");
            }
            else {
                elem.removeClass("ui-widget-content");
                elem.addClass("ui-state-highlight");
            }
        }
    }
    else {
        alert("Aleady reached maximum travelers: 5");
    }

    return false;
}

function RemoveTraveler() {
    var id = this.id.substring(this.id.indexOf('_') + 1);
    $("table tr").regex("id", "^Traveler_" + id + "$").remove();

    // fix the alternating id
    for (var i = parseInt(id) + 1; i < window.travelersCount; i++) {
        var trElem = $("table tr").regex("id", "^Traveler_" + i + "$");

        trElem.attr("id", "Traveler_" + (i - 1));
        trElem = $("#Traveler_" + (i - 1));
        trElem.html(trElem.html().replace(new RegExp("\\[" + i + "\\]", "g"), "[" + (i - 1) + "]").replace(new RegExp("_" + i, "g"), "_" + (i - 1)));

        var removeButtonElem = $("input").regex("id", "^RemoveTraveler_" + (i - 1) + "$");
        //            removeButtonElem.attr("id", "RemoveTraveler_" + (i - 1));
        removeButtonElem.click(RemoveTraveler);
    }

    window.travelersCount--;

    // fix the alternating row color
    for (var i = 0; i < window.travelersCount; i++) {
        var elem = $("table tr").regex("id", "^Traveler_" + i + "$");

        if (i % 2 == 0) {
            elem.removeClass("ui-state-highlight");
            elem.addClass("ui-widget-content");
        }
        else {
            elem.removeClass("ui-widget-content");
            elem.addClass("ui-state-highlight");
        }
    }

    return false;
}

function OffersBegin() {

//    $('#FromStationName').attr('value', $('#ldFromStation').attr('value'));
//    $('#ToStationName').attr('value', $('#ldToStation').attr('value'));
    
    $('#offers-content').html("");
    $('#client-data-content').html("");
    $('#payment-content').html("");
    $('#ticket-content').html("");
    $.blockUI({
        css:
        {
            width: '700px',
            height: '500px',
            top:  ($(window).height() - 500) /2 + 'px', 
            left: ($(window).width() - 700) /2 + 'px'
        },
        message: $('#loading')
    });
}
function OffersSuccess() {
    $.unblockUI();
    $('offers').append('<div style="clear:both"></div>');
    $('a[href="#offers"]').triggerHandler('click');
    $('a[href="#offers"]').triggerHandler('change');

    //$('#tabs').find(window.tabASelector).eq(idx).triggerHandler('change');
    
    //$('#tabs').tabs('select', '#offers');
}

function OffersFailure() {
    $.unblockUI();
    alert("Error occured!");
}

$(document).ready(function () {
//    $('#ldFromStation').attr('name', 'FromStationName');
//    $('#ldToStation').attr('name', 'ToStationName');

    var dFormat = 'mm/dd/yy';
    var timeFormat = 'hh:mm';
    if (region == 'de') {
        dFormat = 'dd.mm.yy';
    }
    else if (region == 'fr' || region == 'it') {
        dFormat = 'dd/mm/yy';
    }
    else {
        timeFormat = 'h:mm TT';
    }
    $.datepicker._defaults.dateFormat = dFormat;
    var dates = $("#FromDate, #ToDate").datetimepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 3,
        minDate: 0,
        maxDate: "+3M",
        showWeek: true,
        firstDay: 1,
        showOn: "button",
        buttonImage: "Content/images/calendar.gif",
        dateFormat: dFormat,
        timeFormat: timeFormat,
        create: function (event, ui) {
            var i = 9;
        },
        onSelect: function (selectedDate, inst) {
            if (inst.id) {
                var dateComponents = selectedDate.split(" ");
                var dateComp = dateComponents[0];
                var timeComp = dateComponents[1];
                var option = this.id == "FromDate" ? "minDate" : "maxDate";
                var instance = $(this).data("datepicker");
                var date = $.datepicker.parseDate(
						    instance.settings.dateFormat ||
						    $.datepicker._defaults.dateFormat,
						    dateComp, instance.settings);
                dates.not(this).datepicker("option", option, date);
            }
        }
    });

    dates.datepicker("option", $.datepicker.regional[region]);
    dates.datetimepicker("option", $.timepicker.regional[region]);
    //$.timepicker.setDefaults($.timepicker.regional[region]);

    //    $('#FromDate').focusout(function() {
    //        alert('FromDate .change() called.');
    //    });

    //    $('#ToDate').focusout(function() {
    //        alert('ToDate .change() called.');
    //    });

    $("input").regex("id", "^AddNewTraveler_\\d+$").click(AddTraveler);
    $("input").regex("id", "^RemoveTraveler_\\d+$").each(function () {
        $(this).click(RemoveTraveler);
    });
});